package com.demo.mantis.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.techarts.dragonfly.app.helper.Converter;

@WebServlet("/calculator")
public class CalculatorServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		float x = Converter.toFloat(request.getParameter("x"));
		float y = Converter.toFloat(request.getParameter("y"));
		String op = request.getParameter("op").toLowerCase();
		response.setContentType("application/jason");
		switch (op) {
			case "plus":
				var result = x + y;
				response.getWriter().write(result + "");
				break;
			case "subtract":
				result = x - y;
				response.getWriter().write(result + "");
				break;
			case "multiply":
				result = x * y;
				response.getWriter().write(result + "");
				break;
			case "divide":
				if (y != 0) {
					float quotient = x / y;
					response.getWriter().write(quotient + "");
				} else {
					response.getWriter().write("\"Divide by 0\"");
				}
				break;
			default:
				response.getWriter().write("\"Unsupported operator\"");
		}
	}
}
